package com.iyao_app.mvp.storywall;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import com.amap.api.maps.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.iyao_app.R;
import com.iyao_app.adapter.StoryWallAdapter;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.Manor;
import com.iyao_app.entry.PageInfo;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.StoryData;
import com.iyao_app.entry.StoryDetail;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.mvp.storydetail.StoryDetailActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.MessageEvent;
import com.iyao_app.util.ResourcesUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.PopupWindowUtils;
import com.iyaowoqu.base_library.util.SPUtils;
import com.iyaowoqu.base_library.util.ScreenUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 : 胡家兵
 * 时间 : 2017/11/9.
 */

public class StoryWallActivity extends BaseActivityWithHead implements StoryWallContract.View, OnRefreshLoadmoreListener {

    @BindView(R.id.main_content)
    LinearLayout main_content;
    @BindView(R.id.x_recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.lin_empty)
    LinearLayout mLinEmpty;

    private int page = 1;
    private PageInfo pageInfo;
    private final int pageSize = 10;
    private Manor manor;

    private StoryWallContract.Presenter mPresenter;
    private StaggeredGridLayoutManager manager;
    private StoryWallAdapter adapter;
    private LatLng myLatlng;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_story_wall);
        ButterKnife.bind(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        new StoryWallPresenter(this);
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upDate(MessageEvent event) {
        if (event.getState() == MessageEvent.PUBLISH) {
            getData(true);
        } else if (event.getState() == MessageEvent.UPDATE_STORY) {
            StoryDetail message = (StoryDetail) event.getMessage();
            int position = message.position;
            StoryDetail storyDetail = adapter.getData().get(position);
            storyDetail.goodVote = message.goodVote;
            storyDetail.goodCount = message.goodCount;
            storyDetail.commentCount = message.commentCount;
            adapter.notifyItemChanged(position);
        }
    }

    private void initData() {
        manor = (Manor) getIntent().getSerializableExtra(Contants.THIRD_FIELD);
        myLatlng = getIntent().getParcelableExtra(Contants.TYPE);

        setTitleTV(ResourcesUtils.getString(R.string.story_wall));
        setNextImage(R.mipmap.btn_bianji);
        onNextClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StoryWallActivity.this, PublishStoryActivity.class);
                intent.putExtras(getIntent());
                startActivity(intent);
            }
        });


        manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        adapter = new StoryWallAdapter(null, myLatlng);
        manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                manager.invalidateSpanAssignments(); //防止第一行到顶部有空白区域
            }
        });

        adapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        adapter.isFirstOnly(true);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LogUtil.e("=============================================");
                StoryDetail item = (StoryDetail) adapter.getItem(position);
                item.position = position;
                LogUtil.e("=====item.position====" + item.position);
                if (item != null) {
                    LogUtil.e("====" + item.toString());
                    Intent intent = new Intent(StoryWallActivity.this, StoryDetailActivity.class);
                    intent.putExtra(Contants.TYPE, item.id);
                    intent.putExtra(Contants.CLASS_TYPE, item);
                    startActivity(intent);
                }
            }
        });
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.autoRefresh();


    }

    @Override
    protected void onStart() {
        super.onStart();

        Observable.timer(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new Consumer<Long>() {

                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (StoryWallActivity.this != null &&!StoryWallActivity.this.isFinishing()) {
                            boolean homeFirst = SPUtils.getInstance().getBoolean(Contants.STORY_FIRST, true);
                            if (homeFirst) {
                                fistEnter();
                            }
                        }

                    }
                });
    }


    @Override
    public void refreshData() {

    }

    @Override
    public void setPresenter(StoryWallContract.Presenter presenter) {
        mPresenter = presenter;
        mPresenter.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        recyclerView = null;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hidProgress() {

    }

    private void getData(final boolean isRefesh) {
        if (manor == null) {
            return;
        }
        if (isRefesh) {
            page = 1;
        } else {
            page++;
        }
        NetUtils.getInstance().getEventList(null, manor.sceneId, "2", page, pageSize, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        StoryData storyData = model.getModel();
                        if (storyData != null) {
                            List<StoryDetail> list = storyData.list;
                            pageInfo = storyData.pageInfo;
                            if (pageInfo.pageTotal <= page) {
                                mRefreshLayout.finishLoadmoreWithNoMoreData();
                            } else {
                                mRefreshLayout.finishLoadmore();
                            }
                            if (isRefesh) {
                                mRefreshLayout.finishRefresh();
                            } else {
                                mRefreshLayout.finishLoadmore();
                            }
                            if (list == null || list.size() == 0) {
                                mRefreshLayout.finishLoadmoreWithNoMoreData();
                                LogUtil.e("=====list.size() == 0====");
                                if (isRefesh) {
                                    LogUtil.e("=====isRefeshlist.size() == 0====");
                                    mLinEmpty.setVisibility(View.VISIBLE);
                                    mRefreshLayout.setVisibility(View.GONE);
                                }
                            } else {
                                mLinEmpty.setVisibility(View.GONE);
                                mRefreshLayout.setVisibility(View.VISIBLE);
                                if (isRefesh) {
                                    adapter.getData().clear();
                                }
                                dealData(list);
                            }
                        }
                    }

                }
            }

            @Override
            public void onFail(String message, int code) {
                if (isRefesh) {
                    mRefreshLayout.finishRefresh();
                } else {
                    mRefreshLayout.finishLoadmore();
                }
            }
        }, StoryData.class);
    }

    float maxValue = ResourcesUtils.getDimension(R.dimen.y800);
    float minValue = ResourcesUtils.getDimension(R.dimen.y120);

    private void dealData(List<StoryDetail> list) {
        final int viewWith = (ScreenUtils.getScreenWidth() - 84) / 2;
        if (list != null && list.size() > 0) {
            for (final StoryDetail listBean : list) {
                List<String> eventFileUrlList = listBean.eventFileUrlList;
                if (eventFileUrlList != null && eventFileUrlList.size() > 0) {
                    String s = eventFileUrlList.get(0);
                    try {
                        String[] split = s.split("_");
                        if (split.length > 0) {
                            String wh = split[split.length - 1];
                            String[] split1 = wh.split("\\*");
                            int width = Integer.parseInt(split1[0]);
                            String hStr = split1[1];
                            String[] split2 = hStr.split("\\.");
                            int height = Integer.parseInt(split2[0]);
                            listBean.width = viewWith;
                            int temp = (int) ((float) (viewWith * height) / (float) width);
                            if (temp > maxValue) {
                                listBean.height = (int) maxValue;
                            } else if (temp < minValue) {
                                listBean.height = (int) minValue;
                            } else {
                                listBean.height = temp;
                            }

                        }
                    } catch (Exception e) {

                    }

                }
            }
            adapter.addData(list);
        }

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        getData(false);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        getData(true);
    }


    private void fistEnter() {

        final PopupWindowUtils popupWindowUtils = PopupWindowUtils.getInstance();
        popupWindowUtils.attachActivity(StoryWallActivity.this, R.layout.story_guide, main_content)
                .wiewSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
                .location(Gravity.CENTER)
                .isDarkened(false)
                .Animation(PopupWindowUtils.ANIMATION_DIALOG)
                .setPopupWindowItemViewClickListener(new PopupWindowUtils.SetonPopWindowItemViewClickListenter() {
                    @Override
                    public void onPopWindowItemViewClickListener(int id) {
                        popupWindowUtils.dissMissPopWindow();
                        SPUtils.getInstance().put(Contants.STORY_FIRST, false);
                    }
                }, R.id.v_pop)
                .show();
    }
}
